package com.tk.exam.web.admin;

import com.tk.exam.config.properties.SystemProperties;
import com.tk.exam.domain.TkFile;
import com.tk.exam.http.Response;
import com.tk.exam.service.TkFileService;
import com.tk.exam.utils.SSOUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;


@RestController
@RequestMapping("tk/exam/admin/file")
@Slf4j
public class UploadController {

    @Autowired
    SystemProperties systemProperties;
    @Autowired
    TkFileService tkFileService;

    @PostMapping("/upload")
    public Response upload(@RequestParam("entityType") String entityType, @RequestParam(value = "entityId", required = false) String entityId, @RequestParam("files") MultipartFile[] files) {
        if (files == null || files.length == 0) {
            return Response.fail("无上传文件");
        }
        List<Map> uploadFileList = new ArrayList<>();

        String path = System.currentTimeMillis() + "";
        String absolutePath = systemProperties.getFileUploadPath() + File.separator + path;
        Date now = new Date();
        // 如果文件不为空，写入上传路径，进行文件上传
        for (MultipartFile file : files) {
            String fileName = SSOUtil.generateSid();
            String suffix = getSuffix(file.getOriginalFilename());
            fileName += "." + suffix;
            String relativePath = path + File.separator + fileName;
            // 测试MultipartFile接口的各个方法
            log.info("文件类型ContentType={}", file.getContentType());
            log.info("文件组件名称Name={}", file.getName());
            log.info("文件原名称OriginalFileName={}", file.getOriginalFilename());
            log.info("文件大小Size={}", file.getSize() + "byte or " + file.getSize() / 1024 + "KB");
            try {
                //保存
                File distFile = saveFile(file, absolutePath, fileName);
                //入库
                TkFile tkFile = new TkFile();
                tkFile.setFileName(file.getOriginalFilename());
                tkFile.setFilePath(relativePath);
                tkFile.setFileType(checkImage(distFile) == true ? (byte) 1 : (byte) 2);//1图片;2文件
                tkFile.setEntityType(entityType);
                if(StringUtils.isNotEmpty(entityId)) {
                    tkFile.setEntityId(Integer.parseInt(entityId));
                }
                tkFile.setCreateTime(now);
                tkFile.setUpdateTime(now);
                int fileId = tkFileService.saveTkFile(tkFile);
                //返回json
                Map<String, String> fileMap = new HashMap<>();
                fileMap.put("id", fileId + "");
                fileMap.put("originalFileName", file.getOriginalFilename());
                fileMap.put("fileName", fileName);
                fileMap.put("fileType", suffix);
                fileMap.put("relativePath", relativePath);
                fileMap.put("fileSize", file.getSize() + "");
                uploadFileList.add(fileMap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //返回json
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("files", uploadFileList);
        return Response.succeed(data);
    }


    private File saveFile(MultipartFile file, String path, String fileName) throws IllegalStateException, IOException {
        // 获取上传的文件名称，并结合存放路径，构建新的文件名称
        File filepath = new File(path, fileName);

        // 判断路径是否存在，不存在则新创建一个
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }

        // 将上传文件保存到目标文件目录
        file.transferTo(filepath);

        return filepath;
    }

    private String getSuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public boolean checkImage(File file) {
        try {
            Image image = ImageIO.read(file);
            return image != null;
        } catch (IOException ex) {
            return false;
        }
    }

}
